package com.example.mqltest.config;


import com.example.mqltest.dao.CourseDao;
import com.example.mqltest.dao.StudentDao;
import com.example.mqltest.dao.TeacherDao;
import com.example.mqltest.entity.Result;
import com.example.mqltest.util.SimpleFormatDate;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zhanghong
 * @date 2021/6/10  0010 15:07
 */
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class FileUpload {
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private TeacherDao teacherDao;
    @Value("${prop.upload-folder}")
    private String uploadPath;

    @PostMapping("/uploadWork")
    public Result uploadHead(@RequestParam("files") MultipartFile[] files, @Param("workId") int workId, @Param("studentId") String studentId,@Param( "role" )String role) throws FileNotFoundException {


        String path = uploadPath;

        File filePath = new File( path );
        System.out.println( "文件的保存路径：" + path );
        if (!filePath.exists() && !filePath.isDirectory()) {
            System.out.println( "目录不存在，创建目录:" + filePath );
            filePath.mkdir();
        }

        //将文件保存到服务器指定位置
        try {
            for (int i=0;i<files.length;i++) {
                MultipartFile file=files[i];
                //获取原始文件名称(包含格式)
                String originalFileName = file.getOriginalFilename();
                System.out.println( "原始文件名称：" + originalFileName );

                //获取文件类型，以最后一个`.`为标识
                String type = originalFileName.substring( originalFileName.lastIndexOf( "." ) + 1 );
                System.out.println( "文件类型：" + type );
                //获取文件名称（不包含格式）
                String name = originalFileName.substring( 0, originalFileName.lastIndexOf( "." ) );

                //设置文件新名称: 当前时间+文件名称（不包含格式）
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmss" );
                String date = sdf.format( d );
                String fileName = date + name + "." + type;
                System.out.println( "新文件名称：" + fileName );

                //在指定路径下创建一个文件
                File targetFile = new File( path, fileName );


                file.transferTo( targetFile );
                System.out.println( "上传成功" );
                if(workId!=0) {
                    studentDao.insertWork( originalFileName, fileName, workId, studentId );
                }else{
                    if(role.equals("student")){
                        studentDao.upLoadHead( studentId,fileName );
                    }else{
                        teacherDao.upLoadHead( studentId,fileName );
                    }
                }
                //将文件在服务器的存储路径返回

            }
        } catch (IOException e) {
            System.out.println( "上传失败" );
            e.printStackTrace();
            return new Result( 400, "上传失败", "" );
        }
        courseDao.studentUpdateWorkStatus( studentId,workId,"待批改",  new Date()  );
        return new Result( 200, "上传成功", "" );
    }

    @GetMapping("/download")
    public Object downloadFile(@Param("fileName") String fileName, HttpServletResponse response) {
        OutputStream os = null;
        InputStream is = null;
        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType( "application/x-download;charset=utf-8" );
            //Content-Disposition中指定的类型是文件的扩展名，并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的，点保存后，文件以filename的值命名，
            // 保存类型以Content中设置的为准。注意：在设置Content-Disposition头字段之前，一定要设置Content-Type头字段。
            //把文件名按UTF-8取出，并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码，中文不要太多，最多支持17个中文，因为header有150个字节限制。
            response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes( "utf-8" ), "ISO8859-1" ) );
            //读取流
            File f = new File( uploadPath + fileName );
            is = new FileInputStream( f );
            if (is == null) {
                System.out.println( "下载附件失败，请检查文件“" + fileName + "”是否存在" );
                return new Result( 400, "下载附件失败，请检查文件“" + fileName + "”是否存在", "" );
            }
            //复制
            IOUtils.copy( is, response.getOutputStream() );
            response.getOutputStream().flush();
        } catch (IOException e) {
            return new Result( 400, "下载附件失败", "" );
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //其实，这个返回什么都不重要
        return new Result( 200, "下载附件成功", "" );
    }
    @GetMapping(value = "/getPhoto/{imgUrl}", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getPhoto(@PathVariable("imgUrl") String imgUrl) {
        try {
            File file = new File( uploadPath + imgUrl );
            FileInputStream inputStream = new FileInputStream( file );
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read( bytes, 0, inputStream.available() );
            return bytes;
        }catch (Exception e){
            return null;
        }
    }

}
